package org.newlucene.core.index;

import java.util.Vector;
import java.io.IOException;

import org.newlucene.core.store.Directory;
import org.newlucene.core.store.InputStream;
import org.newlucene.core.store.OutputStream;

final class SegmentInfos
{
	private int counter = 0; // segments_suffix
	private Vector<SegmentInfo> list = new Vector<SegmentInfo>();
   
	public void add(SegmentInfo segInfo)
	{
		list.add(segInfo);
	}
   
	public int size()
	{
		return list.size();
	}

	public void setSize(int newSize)
	{
		list.setSize(newSize);
	}
   
	public int getCounter()
	{
		int result = counter;
		counter++;	// increment counter
		return result;
	}
   
	public final SegmentInfo info(int i)
	{
		return this.list.get(i);
	}

	public final void read(Directory directory) throws IOException
	{
		InputStream input = directory.openFile("segments");
		try
		{
			counter = input.readInt(); // read counter
			for (int i = input.readInt(); i > 0; i--)
			{ 
				// read segmentInfos
				SegmentInfo si = new SegmentInfo(input.readString(), input.readInt(), directory);
				this.list.add(si);
			}
		}
		finally
		{
			input.close();
		}
	}

	public final void write(Directory directory) throws IOException
	{
		OutputStream output = directory.createFile("segments.new");
		try
		{
			output.writeInt(counter); // write counter
			output.writeInt(list.size()); // write infos
			for (int i = 0; i < list.size(); i++)
			{
				SegmentInfo si = info(i);
				output.writeString(si.name);
				output.writeInt(si.docCount);
			}
		}
		finally
		{
			output.close();
		}

		// install new segment info
		directory.renameFile("segments.new", "segments");
	}
}
